package com.rick.awarenessdemo.util

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.PowerManager
import android.provider.Settings
import com.blankj.utilcode.constant.PermissionConstants
import com.blankj.utilcode.util.PermissionUtils
import com.blankj.utilcode.util.ThreadUtils

/**
 * 请求权限工具
 */
object PermissionUtil {

    private var requestCode: Int? = null
    private var onAllGranted: Runnable? = null
    private var onDenied: Runnable? = null

    /**
     * 请求权限
     */
    @JvmStatic
    fun request(activity: Activity, requestCode: Int, onAllGranted: Runnable, onDenied: Runnable) {
        this.requestCode = requestCode
        this.onAllGranted = onAllGranted
        this.onDenied = onDenied
        requestIgnoreBatteryOptimizations(activity, requestCode)
    }

    /**
     * 请求忽略电池优化返回，及后续请求
     */
    @JvmStatic
    fun onActivityResult(activity: Activity, requestCode: Int) {
        if (this.requestCode == requestCode) {
            if (isIgnoreBatteryOptimizations(activity)) {
                requestDrawOverlays {
                    requestManifestPermission(
                        PermissionConstants.LOCATION,
                        PermissionConstants.STORAGE
                    )
                }
            } else {
                requestIgnoreBatteryOptimizations(activity, requestCode)
            }
        }
    }

    /**
     * 是否忽略电池优化（是否允许后台运行）
     */
    @JvmStatic
    private fun isIgnoreBatteryOptimizations(context: Context): Boolean {
        val powerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager
        return powerManager.isIgnoringBatteryOptimizations(context.packageName)
    }

    /**
     * 请求忽略电池优化
     */
    @JvmStatic
    private fun requestIgnoreBatteryOptimizations(activity: Activity, requestCode: Int) {
        val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
        intent.data = Uri.parse("package:${activity.packageName}")
        activity.startActivityForResult(intent, requestCode)
    }

    /**
     * 请求显示在其他应用上层
     */
    @JvmStatic
    private fun requestDrawOverlays(onGranted: Runnable) {
        PermissionUtils.requestDrawOverlays(object : PermissionUtils.SimpleCallback {
            override fun onGranted() {
                onGranted.run()
            }

            override fun onDenied() {
                ThreadUtils.runOnUiThreadDelayed({ requestDrawOverlays(onGranted) }, 1000)
            }
        })
    }

    /**
     * 请求 Manifest.permission 权限
     */
    @JvmStatic
    private fun requestManifestPermission(vararg permission: String) {
        PermissionUtils.permission(*permission).callback(object : PermissionUtils.FullCallback {
            override fun onGranted(p0: MutableList<String>) {
                if (!p0.map { PermissionUtils.isGranted(it) }.contains(false)) {
                    onAllGranted?.run()
                }
            }

            override fun onDenied(
                p0: MutableList<String>,
                p1: MutableList<String>
            ) {
                onDenied?.run()
            }
        }).request()
    }
}